<?php
namespace app\crm\util;
use think\Log;
use function Qiniu\json_decode;

/**
 * 通过HTTPS协议进行服务器间通讯
 */
class HttpsConnection{
    //GET方式发送请求
    protected function sendGetRequest($url)
    {
        Log::record("sendGetRequest:".$url,Log::DEBUG);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        if(!$output){
            Log::record("curl get error:".curl_errno($ch)." message:".curl_error($ch),Log::ERR);
            $this->error="curl get error";
            return false;
        }
        curl_close($ch);
        return $output;
    }
    //POST方式发送请求
    protected function sendPostRequest($url,$data)
    {
        Log::record("sendPostRequest:".$url,Log::DEBUG);
        Log::record("post data:".$data,Log::DEBUG);
        $ch = curl_init(); // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        $output = curl_exec($ch); // 执行操作
        if(!$output){
            Log::record("curl post error:".curl_errno($ch)." message:".curl_error($ch),Log::ERR);
            $this->error="curl post error";
            return false;
        }
        curl_close($ch); // 关闭CURL会话
        return $output;
    }
}